#include "Epik_Input.h"

#include <pspdebug.h>
#include <pspdisplay.h>
#include <pspgu.h>
#include <pspkernel.h>
#include <cstring>
#include <string>
#include <psputility.h>

static unsigned int __attribute__((aligned(16))) list[262144];

Epik_Input::Epik_Input(char *title)
{
	memset(&descText_, 0, TEXT_SIZE__ * sizeof(unsigned short));
	memset(&inText_, 0, TEXT_SIZE__ * sizeof(unsigned short));
	memset(&outText_, 0, TEXT_SIZE__ * sizeof(unsigned short));

	{
		memset(&data_, 0, sizeof(SceUtilityOskData));
		data_.language = PSP_UTILITY_OSK_LANGUAGE_DEFAULT;
		data_.lines = 1;
		data_.unk_24 = 1;
		data_.inputtype = PSP_UTILITY_OSK_INPUTTYPE_ALL;
		data_.desc = descText_;
		data_.intext = inText_;
		data_.outtextlength = TEXT_SIZE__;
		data_.outtextlimit = 32;
		data_.outtext = outText_;
	} {
		memset(&params_, 0, sizeof(params_));
		params_.base.size = sizeof(params_);
		sceUtilityGetSystemParamInt(PSP_SYSTEMPARAM_ID_INT_LANGUAGE, &params_.base.language);
		sceUtilityGetSystemParamInt(PSP_SYSTEMPARAM_ID_INT_UNKNOWN, &params_.base.buttonSwap);
		params_.base.graphicsThread = 17;
		params_.base.accessThread = 19;
		params_.base.fontThread = 18;
		params_.base.soundThread = 16;
		params_.datacount = 1;
		params_.data = &data_;
	}
}


Epik_Input::~Epik_Input()
{}


void Epik_Input::Keyboard()
{
	bool done = false;
	sceUtilityOskInitStart(&params_);

	while(!done)
	{
		sceGuStart(GU_DIRECT, list);
		sceGuClearColor(0);
		sceGuClearDepth(0);
		sceGuClear(GU_COLOR_BUFFER_BIT | GU_DEPTH_BUFFER_BIT);

		sceGuFinish();
		sceGuSync(0,0);

		switch(sceUtilityOskGetStatus())
		{
		case PSP_UTILITY_DIALOG_INIT:
			break;

		case PSP_UTILITY_DIALOG_VISIBLE:
			sceUtilityOskUpdate(1);
			break;

		case PSP_UTILITY_DIALOG_QUIT:
			sceUtilityOskShutdownStart();
			break;

		case PSP_UTILITY_DIALOG_FINISHED:
			break;

		case PSP_UTILITY_DIALOG_NONE:
			done = true;
			break;

		default:
			break;
		}

		sceDisplayWaitVblankStart();
		sceGuSwapBuffers();
	}
}


std::string Epik_Input::GetInput()
{
	std::string input;

	Keyboard();
	switch(data_.result)
	{
	case PSP_UTILITY_OSK_RESULT_CHANGED:
	case PSP_UTILITY_OSK_RESULT_UNCHANGED:
	case PSP_UTILITY_OSK_RESULT_CANCELLED:
		for (int i=0; data_.outtext[i]; i++)
		{
			unsigned c = data_.outtext[i];
			if (32 <= c && c <= 127)
				input += data_.outtext[i];
		}
		break;

	default:
		break;
	}

	return input;
}
